package com.uchengwang.ui.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;

import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.functions.http.listener.OnHttpResultSingleListener;
import com.uchengwang.functions.http.manager.OSSManager;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.shaohui.advancedluban.OnCompressListener;
import me.shaohui.advancedluban.OnMultiCompressListener;


/**
 * Created by U城网 on 2017/7/16.
 */

public class ImageManagerUtils {
    private static ImageManagerUtils utils;

    private ImageManagerUtils (){}
    private boolean isAllow = true;//是否允许再次提交

    public static ImageManagerUtils getUtils() {
        if (utils == null){
            utils = new ImageManagerUtils();
        }
        return utils;
    }


    /**
     * 压缩图片在上传
     * 头像 上传单张图片
     * */
    public void compressAndPost(final Context context, String headUrl, int size, final ImageCompressListener callBack){
        String url = crossAndReturn(headUrl, 600, 800);
        if (TextUtils.isEmpty(url)){
            return;
        }

        if (!isAllow){
            UCommonUtil.getUtil().showToast(context, "正在提交...");
            return;
        }
        isAllow = false;

        UCommonUtil.getUtil().compressImageAlone(context, size, url, new OnCompressListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(File file) {
                String head = file.getAbsolutePath();//压缩后的想地址

                //上传到阿里云
                OSSManager.getOSSManager().putHeadToOss(head, new HttpCallBack() {
                    @Override
                    public void onError(int status, String msg) {
                        LoadingUtils.getUtils().hide();
                        isAllow = true;
                        callBack.onResult(-3, msg, "提交oss失败");
                    }

                    @Override
                    public void onResp(int status, String msg, String data) {
                        //上传成功返回的oss的头像地址
                        isAllow = true;
                        callBack.onResult(0, msg, data);
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                isAllow = true;
                callBack.onResult(-1, null, "压缩失败");
            }
        });
    }

    /**
     * 压缩图片在上传
     * 上传单张图片
     * @param type 1头像  2享说 3U城内容,社团纳新,社团/校吧内的贴子内的图片;
     * */
    public void compressAndPost(final Context context, final int type, String headUrl, int size, final ImageCompressListener callBack){
        String url = crossAndReturn(headUrl, 600, 800);
        if (TextUtils.isEmpty(url)){
            callBack.onResult(-2, null, "拿取路径失败");
            return;
        }
        if (!isAllow){
            UCommonUtil.getUtil().showToast(context, "正在提交...");
            return;
        }
        isAllow = false;
        UCommonUtil.getUtil().compressImageAlone(context, size, url, new OnCompressListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(File file) {
                String head = file.getAbsolutePath();//压缩后的想地址

                //上传到阿里云
                OSSManager.getOSSManager().putAloneImage(type, head, new HttpCallBack() {
                    @Override
                    public void onError(int status, String msg) {
                        isAllow = true;
                        callBack.onResult(-3, msg, "提交oss失败");
                    }

                    @Override
                    public void onResp(int status, String msg, String data) {
                        //上传成功返回的oss的头像地址
                        isAllow = true;
                        callBack.onResult(0, msg, data);
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                isAllow = true;
                callBack.onResult(-1, null, "压缩失败");
            }
        });
    }


    /**
     * 图片集合的压缩上传  先做尺寸压缩
     * @param list 压缩图片的集合
     * @param size 每张图片的压缩大小
     * 返回-1 压缩失败 可以直接上传原图
     * @param type 1头像  2享说 3U城内容,社团纳新,社团/校吧内的贴子内的图片;
     * @param isObjectKey true只需要objectKet  false需要全部
     * */
    public void compressAndPost(final Context context, final int type, final List<String> list, int size, final boolean isObjectKey, final ImageCompressListener callBack){
        List<String> urls = crossAndReturn(list, 600, 800);
        if (urls == null){
            callBack.onResult(-2, null, "拿取路径失败");
            return;
        }

        if (!isAllow){
            UCommonUtil.getUtil().showToast(context, "正在提交...");
            return;
        }
        isAllow = false;
        UCommonUtil.getUtil().compressImageMulti(context, size, urls, new OnMultiCompressListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(List<File> fileList) {
                list.clear();

                for (File file : fileList){
                    try {
                        list.add(file.getAbsolutePath());
                        Log.d("yasuo", "压缩后="+file.getAbsolutePath());
                        Log.d("yasuo", "压缩后="+UCommonUtil.getUtil().getFileSize(file));
                    } catch (Exception e) {
                        e.printStackTrace();
                        isAllow = true;
                        callBack.onResult(-2, null, "拿取路径失败");
                        return;
                    }
                }

                if (list != null && list.size() >0){
                    OSSManager.getOSSManager().putAsyncFiles(type, list, new OSSManager.OSSListener() {
                        @Override
                        public void onProgress(long currentSize, long totalSize) {
                            //不是整个集合图片的上传进度，是单张图片的上传进度
                        }
                        @Override
                        public void onSuccess(List<String> ossList) {
                            //上传oss成功返回的oss图片地址集合 因为地址需要拼接在一起，所以将objectKey取出提交给服务器，使用时加上BaseConfig.OSS_COM_IMAGE
                            //单张图片提交时，是全地址
                            //将图片集合按照自己服务器格式要求上传  格式 urlA;urlB;
//                            UCommonUtil.getUtil().showToast(context, "图片提交oss成功");
                            isAllow = true;
                            StringBuilder stringBuilder  = new StringBuilder();
                            String roll_imgs = "";
                            if (ossList != null  && ossList.size() >0){
                                String cover_image = UCommonUtil.getUtil().getOssImageUrl(type) + ossList.get(0);
                                for (int i = 0; i< ossList.size(); i++){
                                    String ossUrl = ossList.get(i);
                                    if (i != 0){
                                        stringBuilder.append(";");
                                    }
                                    if (isObjectKey){
                                        stringBuilder.append(ossUrl);
                                    }else {
                                        stringBuilder.append(UCommonUtil.getUtil().getOssImageUrl(type) + ossUrl);
                                    }
                                }
                                if (stringBuilder!= null){
                                    roll_imgs = stringBuilder.toString();
                                }

                                callBack.onResult(0, cover_image, roll_imgs);
                            }

                        }
                        @Override
                        public void onFailure(String message) {
                            Log.d("ucw", "提交失败="+message);
                            isAllow = true;
                            callBack.onResult(-3, null, "提交oss失败");
                        }
                    });
                }

            }

            @Override
            public void onError(Throwable e) {
                isAllow = true;
                callBack.onResult(-1, null, "压缩失败");
            }
        });
    }


    /**
     * 图片集合的压缩上传  先做尺寸压缩
     * @param list 压缩图片的集合
     * @param size 每张图片的压缩大小
     * 返回-1 压缩失败 可以直接上传原图
     * @param type 1头像  2享说 3U城内容,社团纳新,社团/校吧内的贴子内的图片;
     * @param isObjectKey true只要key
     * */
    public void compressAndPost(final Context context, final int type, final List<String> list, int size, final boolean isObjectKey, final OnHttpResultListener<String> callBack){
        List<String> urls = crossAndReturn(list, 600, 800);
        if (urls == null){
            callBack.onResult(-2, null, 0, null);
            return;
        }

        if (!isAllow){
            UCommonUtil.getUtil().showToast(context, "正在提交...");
            return;
        }
        isAllow = false;
        UCommonUtil.getUtil().compressImageMulti(context, size, urls, new OnMultiCompressListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(List<File> fileList) {
                list.clear();

                for (File file : fileList){
                    try {
                        list.add(file.getAbsolutePath());
                        Log.d("yasuo", "压缩后="+file.getAbsolutePath());
                        Log.d("yasuo", "压缩后="+UCommonUtil.getUtil().getFileSize(file));
                    } catch (Exception e) {
                        e.printStackTrace();
                        isAllow = true;
                        callBack.onResult(-2, null, 0, null);
                        return;
                    }
                }

                if (list != null && list.size() >0){
                    OSSManager.getOSSManager().putAsyncFiles(type, list, new OSSManager.OSSListener() {
                        @Override
                        public void onProgress(long currentSize, long totalSize) {
                            //不是整个集合图片的上传进度，是单张图片的上传进度
                        }
                        @Override
                        public void onSuccess(List<String> ossList) {
                            //上传oss成功返回的oss图片地址集合 因为地址需要拼接在一起，所以将objectKey取出提交给服务器，使用时加上BaseConfig.OSS_COM_IMAGE
                            //单张图片提交时，是全地址
                            //将图片集合按照自己服务器格式要求上传  格式 urlA;urlB;
                            isAllow = true;
                            if (ossList != null  && ossList.size() >0){
                                List<String> resultList = new ArrayList<>();
                                for (int i = 0; i< ossList.size(); i++){
                                    String ossUrl = ossList.get(i);

                                    if (isObjectKey){
                                        resultList.add(ossUrl);
                                    }else {
                                        resultList.add(UCommonUtil.getUtil().getOssImageUrl(type) + ossUrl);
                                    }
                                }

                                callBack.onResult(0, "", 0, resultList);
                            }


                        }
                        @Override
                        public void onFailure(String message) {
                            Log.d("ucw", "提交失败="+message);
                            isAllow = true;
                            callBack.onResult(-3, null, 0, null);
                        }
                    });
                }

            }

            @Override
            public void onError(Throwable e) {
                isAllow = true;
                callBack.onResult(-1, null, 0, null);
            }
        });
    }

    /**
     * 直接压缩上传图文交叉信息
     * */
    public void postCrossImagesAndText(final Context context, final int type, final List<String> list, int size, final ImageCompressListener callBack){

    }

    /**
     * 根据压缩图片地址集合 尺寸压缩后返回
     * */
    public List<String> crossAndReturn(List<String> list, int width, int height){
        List<String> saveUrls = null;
        if (list != null && list.size() >0){
            saveUrls = new ArrayList<>();
            for (String path : list){
                Bitmap bitmap = crossSize(path, width, height);
                String saveUrl = save(bitmap, PathUtils.getUtils().getCropImagePath(path));
                saveUrls.add(saveUrl);
            }
        }else {
            return null;
        }
        return saveUrls;
    }

    /**
     * 根据单张图片地址 尺寸压缩后返回
     * */
    public String crossAndReturn(String crossUrl, int width, int height){
        if (!TextUtils.isEmpty(crossUrl)){
            Bitmap bitmap = crossSize(crossUrl, width, height);
            String saveUrl = save(bitmap, PathUtils.getUtils().getCropImagePath(crossUrl));

            return saveUrl;
        }else {
            return null;
        }
    }


    /**
     * 将图片按尺寸压缩
     * @param path 要压缩的图片地址
     * @param width 压缩后的宽度
     * @param height 压缩后的高度
     * */
    public Bitmap crossSize(String path, int width, int height){
        // 获取option
        BitmapFactory.Options options = new BitmapFactory.Options();
        // inJustDecodeBounds设置为true,这样使用该option decode出来的Bitmap是null，
        // 只是把长宽存放到option中
        options.inJustDecodeBounds = true;
        // 此时bitmap为null
        BitmapFactory.decodeFile(path, options);
        int inSampleSize = 1; // 1是不缩放
        // 计算宽高缩放比例
        int inSampleSizeW = options.outWidth / width;
        int inSampleSizeH = options.outHeight / height;
        // 最终取大的那个为缩放比例，这样才能适配，例如宽缩放3倍才能适配屏幕，而
        // 高不缩放就可以，那样的话如果按高缩放，宽在屏幕内就显示不下了
        if (inSampleSizeW > inSampleSizeH) {
            inSampleSize = inSampleSizeW;
        }else {
            inSampleSize = inSampleSizeH;
        }
        // 设置缩放比例
        options.inSampleSize = inSampleSize;
        // 一定要记得将inJustDecodeBounds设为false，否则Bitmap为null
        options.inJustDecodeBounds = false;
        Bitmap bitmap  = BitmapFactory.decodeFile(path, options);

        return bitmap;
    }

    /***
     * @param bitmap 要保存的bitmap
     *@param targetPath 压缩后存储的地址
     * */
    public String save(Bitmap bitmap, String targetPath){
        File outputFile = new File(targetPath);
        try {
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
            } else {
                outputFile.delete();
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            bitmap.recycle();
        } catch (Exception e) {
            Log.d("jjf", "错误信息="+e.getMessage());
            return null;
        }
        return outputFile.getAbsolutePath();
    }


    /**
     * 将图片压缩在上传
     * */
//    private int position = 0;
//    public List<SEditorData> cropmpress(final Context context, final List<SEditorData> list, final ImageCompressListener callBack){
//        if (position >= list.size()){
//            putEditData(context, list, callBack);
//            return list;
//        }
//        final SEditorData data = list.get(position);
//        if (TextUtils.isEmpty(data.getType()) || TextUtils.isEmpty(data.getContent())){
//            list.remove(data);
//            cropmpress(context, list, callBack);
//            return null;
//        }
//
//        if (!data.getType().equals("0") || TextUtils.isEmpty(data.getContent())) {
//            position++;
//            cropmpress(context, list, callBack);
//            return null;
//        }
//        final String path = data.getContent();
//        UCommonUtil.getUtil().compressImageAlone(context, 300, path, new OnCompressListener() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void onSuccess(File file) {
//                Log.d("lll", "压缩="+position);
//                Log.d("kkk", "原图地址="+path);
//                Log.d("kkk", "压缩地址="+file.getAbsolutePath());
//                list.get(position).setContent(file.getAbsolutePath());
//                position++;
//
//                if (position >= list.size()) {
//                    putEditData(context, list, callBack);
//                    return;
//                }
//                cropmpress(context, list, callBack);
//            }
//            @Override
//            public void onError(Throwable e) {
//                putEditData(context, list, callBack);//压缩失败直接上传原图
//            }
//        });
//        return null;
//    }
//
//
//    /**
//     * 负责处理编辑数据提交等事宜，请自行实现
//     */
//    private boolean isAllow;
//    private void putEditData(Context context, List<SEditorData> editList, final ImageCompressListener callBack) {
//        if (editList == null || editList.size() <= 0){
//            UCommonUtil.getUtil().showToast(context, "请编辑公益内容");
//            isAllow = true;
//            return;
//        }
//        Log.d("lll", "开上");
//        //图片上传阿里云oss后的返回
//        OSSManager.getOSSManager().putSortRichImages(OSSManager.OSS_CITY, editList, new SortRichListener() {
//            @Override
//            public void onsuccess(List<SEditorData> list) {
//                int size = list.size();
//
//                if (list != null && size > 0){
//                    //图文交叉排布的所有内容， 上传到我们服务器
//                    stringContent = JsonUtils.getManager().beanToString(list);
//
//                    for (int i = 0; i < size; i++) {
//                        SEditorData data = list.get(i);//0图片  1文字
//                        if (data.getType().equals("1") && !TextUtils.isEmpty(data.getContent()) && !isShortDesc) {
//                            shortDesc = data.getContent();
//                            if (shortDesc.length() >40){
//                                shortDesc = shortDesc.substring(0, 40);
//                            }
//                            isShortDesc = true;
//                            Log.d("RichEditor", "commit inputStr=" + data.getContent());
//                        }
//                        if (data.getType() .equals("0") && !TextUtils.isEmpty(data.getContent()) && !isCover) {
//                            cover = data.getContent();
//                            isCover = true;
//                            Log.d("RichEditor", "commit imgePath=" + data.getContent());
//                        }
//                        if (isShortDesc && isCover){
//                            break;
//                        }
//                    }
//
//                }
//            }
//            @Override
//            public void onFailure(String message) {
//                isAllow = true;
//                LoadingUtils.getUtils().hide();
//            }
//        });
//    }



    /**
     * 获取图片宽高 ios加载图片使用
     * */
    public  int[] getImageWH(String path){
        BitmapFactory.Options options = new BitmapFactory.Options();
        /**
         * 最关键在此，把options.inJustDecodeBounds = true;
         * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
         */
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回的bitmap为null
        /**
         *options.outHeight为原始图片的高
         */
        return new int[]{options.outWidth,options.outHeight};
    }

    /**
     * 微信转发用的 先把图片转为file  在压缩到30K 在转为bitmap
     * */
    public void wxShareBitmap(Context context, Bitmap bm, String path, String fileName, final OnHttpResultSingleListener listener){
        File file = bitmapToFile(bm, path, fileName);
        UCommonUtil.getUtil().compressImageAlone(context, 30, file, new OnCompressListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(File file) {
                Bitmap b = BitmapFactory.decodeFile(file.getAbsolutePath());
                Bitmap thumbBmp = Bitmap.createScaledBitmap(b, 60, 60, true);
                listener.onResult(0, null, thumbBmp);
            }

            @Override
            public void onError(Throwable e) {
                listener.onResult(0, null, null);
            }
        });
    }

    /**
     * 将bitmap转为file
     * */
    public File bitmapToFile(Bitmap bm,String path, String fileName){
        File dirFile = new File(path);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path , fileName);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        try {
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return myCaptureFile;
    }




    public interface ImageCompressListener{
        void onResult(int stutas, String cover, String result);
    }

}
